package com.duff.download.okdownload.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * author：duff
 * version：1.0.0
 * date：2017/8/27
 */
public class Utils {

    /**
     * url 合法性检查
     *
     * @param url
     * @return
     */
    public static boolean isHttpUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        String lowCase = url.toLowerCase();

        return lowCase.startsWith("http://") || lowCase.startsWith("https://");
    }

    /**
     * 根据url得到文件名
     *
     * @param url
     * @return
     */
    public static String getFileName(String url) {
        String result = "";
        int i = 0;
        while (i < 1) {
            int lastFirst = url.lastIndexOf('/');
            result = url.substring(lastFirst) + result;
            url = url.substring(0, lastFirst);
            i++;
        }
        return result.substring(1);
    }

    /**
     * String array to string list
     * @param array
     * @return
     */
    public static List<String> stringArray2list(String[] array) {
        if (array == null) {
            return new ArrayList<>();
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            list.add(array[i]);
        }
        return list;
    }

    /**
     * String list to string array
     * @param list
     * @return
     */
    public static String[] list2StringArray(List<String> list) {
        if (list == null) {
            return new String[]{};
        }
        int size = list.size();
        String[] strArray = new String[size];
        for (int i = 0; i < size; i++) {
            strArray[i] = list.get(i);
        }
        return strArray;
    }

    /**
     * 是否存在有效的网络连接.
     *
     * @return 存在有效的网络连接返回true，否则返回false
     */
    public static boolean isNetWorkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return networkConnected(connectivityManager.getActiveNetworkInfo());
    }

    private static boolean networkConnected(NetworkInfo networkInfo) {
        return networkInfo != null && networkInfo.isConnected();
    }

}
